package cn.tx.erp.sys.controller;

import cn.tx.erp.sys.domain.Permission;
import cn.tx.erp.sys.domain.User;
import cn.tx.erp.sys.service.PermissionService;
import cn.tx.erp.sys.service.RoleService;
import cn.tx.erp.sys.service.UserService;
import cn.tx.erp.sys.tree.TreeNode;
import cn.tx.erp.sys.tree.TreeNodeBuilder;
import cn.tx.erp.sys.utils.Constast;
import cn.tx.erp.sys.utils.DataGridView;
import cn.tx.erp.sys.utils.ResultObj;
import cn.tx.erp.sys.utils.WebUtils;
import cn.tx.erp.sys.vo.PermissionVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 菜单管理
 * @author Mxb
 * @version 1.0
 * @date 2020/1/30 17:20
 */
@RestController
@RequestMapping("menu")
public class MenuController {
    @Autowired
    private PermissionService permissionService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserService userService;

    /**
     * 加载登录成功之后首页左侧 的菜单
     * @param sysPermissionVo
     * @return
     */
    @RequestMapping("loadIndexLeftMenuJson")
    public DataGridView loadIndexLeftMenuJson(PermissionVo sysPermissionVo) {
        //查询所有菜单
        QueryWrapper<Permission> qw = new QueryWrapper<>();
        //设置只能查询菜单
        qw.eq("type", Constast.TYPE_MENU); //menu
        qw.eq("available", Constast.AVAILABLE_TRUE); //1 可用

        User user = (User) WebUtils.getSession().getAttribute("user");
        List<Permission> list = null;
        if (user.getType() == Constast.USER_TYPE_SUPER) { //0 超管
            //如果是超管，直接查询
            list = permissionService.list(qw);
        } else {
            //根据用户ID+角色+权限去查询 
            list = permissionService.list(qw);
            Integer userId = user.getId();
            List<Integer> roleList = roleService.queryUserRoleIdsByUid(userId);

            // 根据角色id 取到权限和菜单id
            Set<Integer> set = new HashSet<>();
            for (Integer rid : roleList) {
                List<Integer> permissionList = roleService.queryRolePermissionByRid(rid);
                set.addAll(permissionList);
            }
            // 根据角色id 查询权限
            if (set.size() > 0) {
                qw.in("id", set);
                list = permissionService.list(qw);
            } else {
                list = new ArrayList<>();
            }

        }
        //List<Permission> list = permissionService.list(qw);
        //将他转换为树结点
        List<TreeNode> treeNodes = new ArrayList<>();
        for (Permission p : list) {
            Integer id = p.getId();
            Integer pid = p.getPid();
            String title = p.getTitle();
            String icon = p.getIcon();
            String href = p.getHref();
            Boolean spread = p.getOpen() == 1 ? true : false;
            treeNodes.add(new TreeNode(id, pid, title, icon, href, spread));
        }
        //构造层级关系
        List<TreeNode> list2 = TreeNodeBuilder.build(treeNodes, 1);
        return new DataGridView(list2);
    }

    /*********************菜单管理开始******************************************/

    /**
     * 加载菜单管理左边的菜单树的json
     */
    @RequestMapping("loadMenuManagerLeftTreeJson")
    public DataGridView loadMenuManagerLeftTreeJson(PermissionVo permissionVo) {
        QueryWrapper<Permission> qw = new QueryWrapper<>();

        qw.eq("type", Constast.TYPE_MENU);
        List<Permission> list = this.permissionService.list(qw);
        List<TreeNode> treeNodes = new ArrayList<>();
        for (Permission menu : list) {
            Boolean spread = menu.getOpen() == 1 ? true : false;
            treeNodes.add(new TreeNode(menu.getId(), menu.getPid(), menu.getTitle(), spread));
        }
        // 构造返回数据
        return new DataGridView(0, "", 0L, treeNodes);
    }

    /**
     * 查询所有的菜单
     */
    @RequestMapping("loadAllMenu")
    public DataGridView loadAllMenu(PermissionVo permissionVo) {
        // 分页查询
        IPage<Permission> page = new Page<>(permissionVo.getPage(), permissionVo.getLimit());

        // 构造查询条件
        QueryWrapper<Permission> qw = new QueryWrapper<>();
        qw.eq("type", Constast.TYPE_MENU);


        qw.like(StringUtils.isNotBlank(permissionVo.getTitle()), "title", permissionVo.getTitle());
        qw.eq(permissionVo.getId() != null, "id", permissionVo.
                getId()).or().eq(permissionVo.getId() != null, "pid", permissionVo.getId());
        qw.orderByAsc("ordernum");

        // 调用方法查询
        this.permissionService.page(page, qw);
        // 返回数据
        return new DataGridView(0, "", page.getTotal(), page.getRecords());
    }

    /**
     * 加载最大的排序码
     * @return
     */
    @RequestMapping("loadMenuMaxOrderNum")
    public Map<String, Object> loadMenuMaxOrderNum() {
        Map<String, Object> map = new HashMap<String, Object>();
        // 构造查询条件
        QueryWrapper<Permission> qw = new QueryWrapper<>();
        qw.orderByDesc("ordernum");
        IPage<Permission> page = new Page<>(1, 1);
        List<Permission> list = this.permissionService.page(page, qw).getRecords();
        if (list.size() > 0) {
            map.put("value", list.get(0).getOrdernum() + 1);
        } else {
            map.put("value", 1);
        }
        return map;
    }


    /**
     * 添加
     * @param permissionVo
     * @return
     */
    @RequestMapping("addMenu")
    public ResultObj addMenu(PermissionVo permissionVo) {
        try {
            permissionVo.setType(Constast.TYPE_MENU);//设置添加类型
            this.permissionService.save(permissionVo);
            return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERR;
        }
    }


    /**
     * 修改
     * @param permissionVo
     * @return
     */
    @RequestMapping("updateMenu")
    public ResultObj updateMenu(PermissionVo permissionVo) {
        try {
            this.permissionService.updateById(permissionVo);
            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDATE_ERR;
        }
    }


    /**
     * 查询当前的ID的菜单有没有子菜单
     */
    @RequestMapping("checkMenuHasChildrenNode")
    public Map<String, Object> checkMenuHasChildrenNode(PermissionVo permissionVo) {
        Map<String, Object> map = new HashMap<String, Object>();
        // 构造查询条件
        QueryWrapper<Permission> qw = new QueryWrapper<>();
        qw.eq("pid", permissionVo.getId());
        List<Permission> list = this.permissionService.list(qw);
        if (list.size() > 0) {
            map.put("value", true);
        } else {
            map.put("value", false);
        }
        return map;
    }

    /**
     * 删除
     * @param permissionVo
     * @return
     */
    @RequestMapping("deleteMenu")
    public ResultObj deleteMenu(PermissionVo permissionVo) {
        try {
            this.permissionService.removeById(permissionVo.getId());
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERR;
        }
    }

    /****************菜单管理结束****************/
}
